package com.sas.utils;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import com.sas.domain.Address;
import com.sas.domain.Flow;
import com.sas.domain.Telephone;

public class Formatter {
	
	private static final String NULL = "-";

	public static String format(Address address) {
		if (address == null) {
			return NULL;
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append(address.getStreet() == null ? "" : address.getStreet()).append(", ")
			.append(address.getNumber() == null ? "" : address.getNumber()).append(", ")
			.append(address.getCity() == null ? "" : address.getCity()).append(", ")
			.append(address.getDepartment() == null ? "" : address.getDepartment()).append(", ")
			.append(address.getProvince() == null ? "" : address.getProvince()).append(", ")
			.append(address.getCountry() == null ? "" : address.getCountry());
		
		if (address.getPostalCode() != null && !address.getPostalCode().isEmpty()) {
			sb.append(" (").append(address.getPostalCode()).append(")");
		}
		
		return sb.toString();
	}


	public static String getLastBuy(Set<Flow> history, Flow.FlowType type) {
		if (history == null || history.isEmpty()) {
			return NULL;
		}
		
		TreeSet<Flow> aux= new TreeSet<Flow>(new Comparator<Flow>() {

			@Override
			public int compare(Flow o1, Flow o2) {
				if (o1.getDate().isEqual(o2.getDate().getMillis())) {
					return 0;
				}
				
				if (o1.getDate().isBefore(o2.getDate().getMillis())) {
					return -1;
				}
				
				return 1;
			}
		});
		
		Iterator<Flow> it = history.iterator();
		while (it.hasNext()) {
			Flow f = it.next();
			if (type.equals(f.getFlowType())) {
				aux.add(f);
			}
		}
		
		if (aux.size() == 0) {
			return NULL;
		}
		
		return aux.first().getDate().toString("yyyy-MM-dd");
	}

	public static String format(Telephone telephone) {
		if (telephone == null) {
			return NULL ;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("(")
			.append(telephone.getCountryCode() == null ? "" : telephone.getCountryCode())
			.append(telephone.getAreaCode() == null ? "" : telephone.getAreaCode()).append(")")
			.append(telephone.getTelephoneNumber() == null ? "" : telephone.getTelephoneNumber());
		
		if (telephone.getIntern() != null && !telephone.getIntern().isEmpty()) {
			sb.append(" int. ").append(telephone.getIntern());
		}
		
		return sb.toString();
	}

}
